package some.message.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import some.message.dao.MessageDao;
import some.message.domain.MessageCommand;
import some.talk.util.PagingUtil;

@Controller

public class MessageListController {
	
	private int pageSize = 10;
	private int blockCount = 10;
	
	@Autowired
	private MessageDao messageDao;
	
	@RequestMapping("/messageForm.do")
	public ModelAndView form(@RequestParam(value="method",defaultValue="receiverid")String method,@RequestParam(value="pageNum",defaultValue="1")int currentPage,HttpSession session){

		String pagingHtml = "";
		String id = (String)session.getAttribute("id");
		ModelAndView mav = new ModelAndView();
		Map<String,Object> ids = new HashMap<String,Object>();
		
		if(id==null||id.equals("")){
			mav.setViewName("redirect:/main.do");
			return mav;
		}
		
		ids.put("id", id);
		ids.put("method",method);
		
		int count = messageDao.getMessageCount(ids);
		
		PagingUtil page = new PagingUtil(null,null,currentPage,count,blockCount,pageSize,"messageForm.do");
		pagingHtml = page.getPagingHtml().toString();
		
		ids.put("start",page.getStartCount());
		ids.put("end", page.getEndCount());
		
		List<MessageCommand> list = null;
		
		if(count>0){
			list = messageDao.getList(ids);
		}else{
			list = Collections.emptyList();
		}
		
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<list.size();i++){
			sb.append(list.get(i).getContent());
			if(list.get(i).getContent().length()>10){
				sb.delete(7, list.get(i).getContent().length());
				sb.append("...");
			}
			list.get(i).setContent(sb.toString());
			sb.delete(0, sb.length());
		}
		
		int number = count-(currentPage-1)*pageSize;
		
		mav.setViewName("messageForm");
		mav.addObject("type",1);
		mav.addObject("messageList",list);
		mav.addObject("number",number);
		mav.addObject("method",method);
		mav.addObject("count",count);
		mav.addObject("pagingHtml",pagingHtml);
		
		return mav;
	}
	
}
